/*
 * Copyright (c) 2022-2027 Variflight All Rights Reserved.
 * ProjectName: feeyoframework
 * FileName: DownloadUtil.kt
 * Author : Erik
 * Email  : erik7@126.com
 * Date   : 2023/7/13 上午10:03
 * Version 1.0
 * Description:
 * 文件下载工具类，应用kotlin协程，回调在主线程
 * LastModified: 2023/7/13 上午10:03
 */

package com.feeyo.groundservice.base_util.upgrade

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.FileOutputStream
import java.io.InputStream

object DownloadUtil {

    /**
     *下载文件
     * @param url
     * @param destPath 目标文件路径
     * @param listener 下载进度listener
     * @param blockSize 下载分块大小
     */
    @JvmStatic
    fun download(url: String, destPath: String, listener: DownloadListener? = null, blockSize: Int = 1024 * 50) {
        GlobalScope.launch(Dispatchers.IO) {
            val request = Request.Builder().url(url).build()

            var ins: InputStream? = null
            var fos: FileOutputStream? = null

            var total: Long
            var current: Long = 0

            try {
                val response = OkHttpClient().newCall(request).execute()
                total = response.body?.contentLength() ?: 0
                ins = response.body?.byteStream()
                fos = FileOutputStream(destPath)
                var numRead: Int
                val buff = ByteArray(blockSize)
                do {
                    numRead = ins?.read(buff) ?: 0
                    if (numRead <= 0) break
                    fos.write(buff, 0, numRead)
                    current += numRead
                    withContext(Dispatchers.Main) {
                        listener?.onProgress(current, total)
                    }
                } while (true)
            } catch (e: Exception) {
                e.printStackTrace()
                listener?.onError(e.message)
            } finally {
                ins?.close()
                fos?.close()
            }
        }
    }

    interface DownloadListener {
        /**
         * @param download 已下载size (bytes)
         * @param total 总大小 (bytes)
         */
        fun onProgress(download: Long, total: Long)
        fun onError(msg: String?)
    }
}